<template>
  <!-- 隐藏登录页 display: none / display: block -->
  <div class="login-page" style="display: none">

    <!-- 二维码显示 -->
    <div id="login_container"></div>

    <el-form ref="form" :model="form" label-width="80px" style="margin-top:15px;">
      <el-form-item label="用户名">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="form.password" type="password"></el-input>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="onSubmit">登录</el-button>
        <el-button @click="reset">取消</el-button>
      </el-form-item>
    </el-form>
    <div>
      <button @click="gotoFeishuAuth" class="unlogin-btn">
        <img src="/img/feishu-logo.png" alt="feishu-logo">
        <span>飞书免登</span>
      </button>
    </div>
  </div>
</template>
<script>
  // 配置数据
  let serverUrl = 'http://localhost:90'
  var domain = 'http://ndzg3n.natappfree.cc'
  
  var backUrl = domain + "/login";
  var config = {
    client_id: "cli_a2dc74533c78500d",
    client_secret: "Otm3Rk0hJGMpwO2lLOgh5e0rIrx7epHh",
    redirect_uri: backUrl
  }
  // 获取url的参数
  function getUrlParams() {
    let str = window.location.search
    console.log('str', str);
    // ?code=051YCH000vmCDN1EmM200Bdl0f3YCH0w:77 str ?
    if (str && str.includes("?") && str.includes("=")) {
      let obj = {}
      str = str.slice(1)
      console.log('str', str);
      if (str.includes("&")) {
        let arr = str.split("&")
        console.log('arr', arr);
        for (let i = 0; i < arr.length; i++) {
          let one = arr[i].split("=")
          obj[one[0]] = one[1]
        }
      } else {
        let one = str.split("=")
        obj[one[0]] = one[1]
      }
      return obj;
    }
  }

  export default {
    data() {
      return {
        form: {
          username: '',
          password: '',
        }
      }
    },
    mounted() {
      this.initPage();
      let params = getUrlParams()
      console.log('params', params);
      // url上没有code数据时
      if (!params || !params.code) {
        // 直接发起免登录
        this.gotoFeishuAuth()
      }
    },
    methods: {
      gotoFeishuAuth(){
        // 调起扫码
        var goto = `https://passport.feishu.cn/suite/passport/oauth/authorize?client_id=${config.client_id}&redirect_uri=${config.redirect_uri}&response_type=code&state=state123456`;
        window.location.href = goto;
      },
      initPage() {
        // 飞书官方文档 https://open.feishu.cn/document/common-capabilities/sso/web-application-sso/qr-sdk-documentation
        const that = this;

        const getToken = (form) => {
          let url = serverUrl + "/getfsToken"
          
          $.ajax({
            type: "post",
            url,
            data: form,
            cache: false,
            async: true,
            beforeSend: function () {
              //等待延迟的函数
            },
            dataType: 'json',
            // dataType: ($.browser.msie) ? "text" : "xml",
            success: (data) => {
              if(data.outDate){
                alert(data.outDate)
                return
              }
              sessionStorage.setItem('token', data.token)
              
              console.log('getfsToken-成功--', data);
              // 跳进首页
              sessionStorage.setItem('isLogin', data.name)
              sessionStorage.setItem('iconUrl', data.avatar_url)
              that.$router.push({
                name: 'home',
                params: data
              })
            },
            fail: function (err) {
              console.log('getfsToken-err--', err);
            }
          })

        }

        const onloadPage = () => {
          let params = getUrlParams()
          console.log('params', params);
          if (params && params.code) {

            // 获取token https://open.feishu.cn/document/common-capabilities/sso/api/get-access_token
            let form = {
              token: sessionStorage.getItem('token'),
              grant_type: "authorization_code",
              client_id: config.client_id,
              client_secret: config.client_secret,
              code: params.code,
              redirect_uri: config.redirect_uri
            }
            getToken(form)
            return
          }

          console.log("-------调起扫码----")
          // 调起扫码
          var goto = `https://passport.feishu.cn/suite/passport/oauth/authorize?client_id=${config.client_id}&redirect_uri=${config.redirect_uri}&response_type=code&state=state123456`;

          // 利用前端网页跳转
          // window.location.href = url;

          var QRLoginObj = QRLogin({
            id: "login_container",
            goto,
            // goto: "https://passport.feishu.cn/suite/passport/oauth/authorize?client_id=cli_a03f23493d39d00e&redirect_uri=https%3A%2F%2Fwww.baidu.com&response_type=code&state=STATE",
            width: "260",
            height: "260",
            style: 'width:260px;height:260px;border:none' //可选的，二维码html标签的style属性
          });
          var handleMessage = function (event) {
            console.error('event', event);
            var origin = event.origin;
            // 使用 matchOrigin 方法来判断 message 是否来自飞书页面
            if (QRLoginObj.matchOrigin(origin)) {
              var loginTmpCode = event.data;
              // 在授权页面地址上拼接上参数 tmp_code，并跳转
              window.location.href = `${goto}&tmp_code=${loginTmpCode}`;
              console.log(loginTmpCode)
            }
          };
          if (typeof window.addEventListener != 'undefined') {
            window.addEventListener('message', handleMessage, false);
          }
          else if (typeof window.attachEvent != 'undefined') {
            window.attachEvent('onmessage', handleMessage);
          }
          // 原文链接：https://blog.csdn.net/xutongbao/article/details/123278795
        }

        onloadPage()
      },
      onSubmit() {
        if(this.form.username && this.form.password) {
          sessionStorage.setItem('isLogin', this.form.username)
          this.$router.push({
            name: 'home',
            params: {
              username: this.form.username
            }
          })
        } else {
          this.$message({
            message: '用户名和密码必填',
            type: 'warning'
          });
        }
      },
      reset() {
        this.form = {
          username: '',
          password: '',
        }
      },
    }
  }
</script>
<style scoped>
.unlogin-btn{
  border: 1px solid #ccc;
  border-radius: 2px;
  width: 100px;
  padding: 5px;
  display: flex;
  margin: 24px auto 0;
}
.unlogin-btn img {
  width: 16px;
  height: 16px;
}
.unlogin-btn span{
  flex: 1;
  margin-left: 5px;
}
.feishu-icon{
  position: absolute;
  top: 0;
  left: 0;
  width: 24px;
  height: 24px;
  border: 1px solid red;
}
.login-page{
  width: 500px;
  padding: 15px;
  border: 1px solid #f5f5f4;
  position: absolute;
  left: 50%;
  top: 50%;
  background: #eee;
  border-radius: 6px;
  transform: translate(-50%, -50%);
}
#login_container{
  border: 2px solid #584a2d;
  width: 260px;
  height: 260px;
  margin: 10px auto;
  border-radius: 3px;
}
</style>
